package coding;

public class Battle
{
	private int totalHunter;
	private int totalMonster;
	private int currentHunter;
	private int currentMonster;
	private boolean isEnd;
	private boolean isCHAlive;
	private boolean isCMAlive;
	private Monster[] m;
	private MonsterHunter[] h;
	private Output o;
	private Manager manager;

	public Battle()
	{
		totalHunter = 1;
		totalMonster = 5;
		currentHunter = 0;
		currentMonster = 0;
		isEnd = false;
		isCHAlive = true;
		isCMAlive = true;
		m = null;
		h = null;
		o= new Output();
		manager = new Manager();
	}

	public Battle (Manager man) 
	{
		manager = man;
		totalHunter = manager.getHunterCount();
		totalMonster = manager.getMonsterCount();
		currentHunter = 0;
		currentMonster = 0;
		isEnd = false;
		isCHAlive = true;
		isCMAlive = true;
		m = manager.getMonstersList();
		h = manager.getHuntersList();
		o= new Output();
		startBattle();
	}

	protected void finalize(){}

	protected void startBattle()
	{
		while(!isEnd)
		{
			if(isCHAlive==true)
				hunterAttack();
			if(isCMAlive==true)
				monsterAttack();
		}
	}

	protected boolean isHunterWin()
	{
		if(isCMAlive == false && isCHAlive== true && currentMonster == (totalMonster-1))
		{
			isEnd = true;
			return true;
		}
		else
			return false;
	}

	protected boolean isMonsterWin()
	{
		if(isCMAlive == true && isCHAlive == false && currentHunter == (totalHunter-1))
		{
			isEnd = true;
			return true;
		}
		else
			return false;
	}

	protected void updateHunterAliveStatus()
	{
		isCHAlive = h[currentHunter].isAlive();
	}

	protected void updateMonsterAliveStatus()
	{
		isCMAlive = m[currentMonster].isAlive();
	}

	protected void monsterAttack()
	{
		AttackControl a = new AttackControl(h[currentHunter], m[currentMonster]);
		String s = a.attackfromMonster ();
		updateHunterAliveStatus();
		if(isCHAlive == false)
		{
			if(isMonsterWin() == true)
				s += result();
			else
			{
				currentHunter++;
				updateHunterAliveStatus();
			}
		}
		o.display(s);
	}

	protected void hunterAttack()
	{
		AttackControl a = new AttackControl(h[currentHunter], m[currentMonster]);
		String s = a.attackfromMH();
		updateMonsterAliveStatus();
		if(isCMAlive == false)
		{
			if(isHunterWin() == true)
				s += result();
			else
			{
				currentMonster++;
				updateMonsterAliveStatus();
			}
		}
		o.display(s);
	}
	
	protected String result()
	{
		if (isHunterWin() == true)
			return ("Win");
		else
			return ("Lose");
	}
}